package com.google.code.p.localspinner;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

import com.google.code.p.localspinner.database.UserdataAdapter;
import com.google.code.p.localspinner.model.Item;
import com.google.code.p.localspinner.model.ItemList;

/**
 * Demonstrates the using a list view in transcript mode
 *
 */
public class NewListBuilder extends ListActivity implements OnClickListener, OnKeyListener {

    private static final int SAVE_ID = Menu.FIRST;
    private static final int USE_ID = Menu.FIRST+1;
    private EditText titleTxt;
    private EditText bodyTxt;
    
    private UserdataAdapter userData;
    
    private ArrayAdapter<String> mAdapter;
    private ArrayList<String> mStrings = new ArrayList<String>();
    private Item[] items = new Item[12];
    private int count = 0;
    private static final String CANCEL = "Cancel";
    private static final android.content.DialogInterface.OnClickListener NO_ACTION_CLICK_LISTENER = 
      new android.content.DialogInterface.OnClickListener(){public void onClick(DialogInterface dialog, int which) {}};
    
      
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, SAVE_ID, 0, "Save this list").setIcon(R.drawable.add);
        menu.add(0, USE_ID, 0, "Use but don't save").setIcon(R.drawable.use);
        return true;
    }
    
    @Override
    public boolean onMenuItemSelected(int featureId, final MenuItem item) {
      if(count < 2){
        showMessage("Your list must have at least 2 items");
        return true;
      }  
      LayoutInflater factory = LayoutInflater.from(this);
      
      final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
      final EditText nameTxt = (EditText) textEntryView.findViewById(R.id.list_name);
          
          
      Dialog dialog = new AlertDialog.Builder(this)
      .setIcon(R.drawable.alert_dialog_icon)
      .setTitle("Enter a name for this list")
      .setNegativeButton(CANCEL, NO_ACTION_CLICK_LISTENER)
      .setPositiveButton("OK", new android.content.DialogInterface.OnClickListener(){
          @Override
          public void onClick(DialogInterface dialog, int which) {
            if(AppUtils.isBlank(nameTxt)){
              showMessage("Please enter a name for your list.");
              return;
            }
            
            final ItemList il = new ItemList();
            il.setListName(nameTxt.getText().toString());
            for(Item i : items){
              if(i != null){
                il.addItem(i);
              }
            }
            switch(item.getItemId()) {
                case USE_ID:
                    SearchHelper.fillList(il, StaticMemory.ITEMS_EXTRAS);
                Intent i = new Intent(NewListBuilder.this, LocalSpinner.class);                
                i.putExtra(SearchHelper.ITEMS, il);
                startActivity(i);
                break;
              case SAVE_ID:
                try {
                  userData.saveItemList(il);
                  showMessage("List saved.");
                } catch (Exception e) {
                  Log.e(NewListBuilder.class.toString(), e.getMessage(), e);
                  showMessage("Unable to save list: "+e.getMessage());
                }
                break;
              }
            }}
          )
          .setView(textEntryView)
          .create();
          dialog.show();
            return true;
        
    }
    
    private void resetInstruction(){
      instructionsTxt.setText("Tips:\n\n" +
          "1. Click the textbox while its on focused to add the item.\n" +
          "2. Long click on an item to remove it.\n" +
          "3. Press the phone menu button to get the save list option.\n");
    }
    
    private TextView instructionsTxt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userData = new UserdataAdapter(this);
        userData.open();
        setContentView(R.layout.newlist);

        instructionsTxt = (TextView) findViewById(R.id.instructions);
        resetInstruction();
        
        mAdapter = new ArrayAdapter<String>(this, R.layout.newlist_item, R.id.item, mStrings);

        setListAdapter(mAdapter);
        
        titleTxt = (EditText) findViewById(R.id.title);
        bodyTxt = (EditText) findViewById(R.id.body);

        titleTxt.setOnClickListener(this);
        titleTxt.setOnKeyListener(this);
        bodyTxt.setOnClickListener(this);
        bodyTxt.setOnKeyListener(this);
        
        getListView().setOnItemLongClickListener(new OnItemLongClickListener(){

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int pos, long arg3) {
                items[pos] = null;
                mAdapter.remove(mAdapter.getItem(pos));
                
                count--;
                if(count==0){
                  resetInstruction();
                }
                return true;
            }
            
        });
        
    }

    public void onClick(View v) {
        sendText();
    }

    private void sendText() {
        if(count >= 12){
            showMessage("You can enter at most 12 items. Long click on an item to delete it.");
            return;
        }
        String title = titleTxt.getText().toString();
        String body = bodyTxt.getText().toString();
        
        if(AppUtils.isBlank(title)){
            return;
        }
        
        Item item = new Item(title, body);
        items[count] = item;
        mAdapter.add(item.toString());
        count++;
        instructionsTxt.setText(null);
        titleTxt.setText("");
        bodyTxt.setText("");
        titleTxt.requestFocus();
    }

    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_CENTER:
                    sendText();
                    return true;
            }
        }
        return false;
    }
    
    @Override
    protected void onDestroy() {
      super.onDestroy();
      userData.close();
    }
    
    private void showMessage(String errorString) {
        Toast text = Toast.makeText(this, 
                errorString, Toast.LENGTH_SHORT);
        text.show();
    }
}
